<template>
  <BasicModal v-bind="$attrs"
              @register="registerModal"
              :title="getTitle"
              @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
import { defineComponent, ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { accountFormSchema } from './account.data';
import { AddApi, EditApi } from '/@/api/set/account';
export default defineComponent({
  name: 'AccountModal',
  components: { BasicModal, BasicForm },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    const isUpdate = ref(true);
    const [registerModal, { setModalProps, closeModal }] = useModalInner((data) => {
      resetFields();
      isUpdate.value = !!data?.isUpdate;
      if (unref(isUpdate)) {
        const keys = [
          'userId',
          'nickName',
          'phonenumber',
          'userName',
          'password',
          'roleIds',
          'status',
          'remark',
          'operatorId',
        ];
        const obj = {};
        const record = data.record;
        for (const key of keys) {
          if (key === 'roleIds') {
            obj[key] = record[key][0] + '';
          } else {
            obj[key] = record[key] || '';
          }
        }
        setFieldsValue(obj);
      }
    });
    const [registerForm, { setFieldsValue, resetFields, validate, validateFields }] = useForm({
      labelWidth: 100,
      schemas: accountFormSchema,
      showActionButtonGroup: false,
      actionColOptions: {
        span: 23,
      },
    });
    const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '编辑账号'));
    async function handleSubmit() {
      try {
        setModalProps({ confirmLoading: true });
        console.log(validateFields(['password']));
        const values = await validate();
        values.roleIds = [Number(values.roleIds)];
        if (values.userId > 0) {
          await EditApi(values);
        } else {
          await AddApi(values);
        }
        closeModal();
        resetFields();
        emit('success');
      } finally {
        setModalProps({ confirmLoading: false });
      }
    }

    return { registerModal, registerForm, getTitle, handleSubmit };
  },
});
</script>
